package cn.rocky.base;

/**
 * ibm面试题 不借助第3个变量交换2个值
 */
public class exchangeNum {

    public static void main(String[] args) {
        exchangeNum1(5, 8);
        System.out.println("==============");
        exchangeNum2(5, 8);
    }

    static void exchangeNum1(int x, int y) {
        printRemark(x, "x的值为");
        printRemark(y, "y的值为");
        x = x + y; // 13
        y = x - y; // 5
        x = x - y; // 8
        printRemark(x, "交换后x的值为");
        printRemark(y, "交换后y的值为");
    }

    private static void printRemark(int x, String printRemark) {
        System.out.println(printRemark + x);
    }

    static void exchangeNum2(int x, int y) {
        printRemark(x, "x的值为");
        printRemark(y, "y的值为");
        // ^ 异或，位相同为0，不同为1 , 可以理解为相加，但是不进位，结果要么是和，要么是差
        x = x ^ y;  // 5 ^ 8 = 0101 ^ 1000 = 1101 = 13
        y = x ^ y;  // 13^ 8 = 1101 ^ 1000 = 0101 = 5
        x = x ^ y;  // 13^ 5 = 1101 ^ 0101 = 1000 = 8
        printRemark(x, "交换后x的值为");
        printRemark(y, "交换后y的值为");
    }
}
